package com.hw.core.system.controller;

import com.hw.core.system.entity.Course;
import com.hw.core.system.entity.CourseType;
import com.hw.core.system.entity.NoteBook;
import com.hw.core.system.entity.User;
import com.hw.core.system.service.CourseService;
import com.hw.core.system.service.CourseTypeService;
import com.hw.core.system.service.NoteBookService;
import com.hw.core.util.PageModel;
import com.hw.core.util.UuidUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("course")
public class CourseController {
    private static final Logger logger = LoggerFactory.getLogger( CourseController.class );
    @Autowired
    private CourseService courseService;
    @Autowired
    private NoteBookService noteBookService;
    @Autowired
    private CourseTypeService courseTypeService;



    @RequiresPermissions(value = "课程查询")
    @GetMapping("list")
    public String list(Model model, Integer page, String name) throws Exception {
        PageModel<Object[]> pageModel =null;
        if (page == null) {
            pageModel = courseService.findCourseFatherAndSon( 1,6,name);
        } else {
            if (page < 1)
                throw new Exception( "参数错误" );
            pageModel = courseService.findCourseFatherAndSon( page,6,name);
        }
        model.addAttribute( "pageModel", pageModel );
        model.addAttribute( "name", name );
        return "course/listCourse";
    }

    @RequiresPermissions(value = "课程查询")
    @PostMapping("show")
    @ResponseBody
    public Course getCourseTextById(Integer id) {
        return courseService.findCourseById( id );
    }

    @RequiresPermissions(value = "课程新增")
    @PostMapping("add")
    @ResponseBody
    public String add(Course course) {
        course.setImg( "/img/course/default.jpg" );
        Subject currentUser = SecurityUtils.getSubject();
        User principal = (User) currentUser.getPrincipal();
        course.setAuthor(principal  );
        courseService.add( course );
        return "添加成功";
    }

    @RequiresPermissions(value = "课程删除")
    @PostMapping("delete")
    @ResponseBody
    public String delete(Integer id) throws Exception {
        Course courseById = courseService.findCourseById( id );
        String img = courseById.getImg();
        courseService.delete( id );
        if (!"/img/course/default.jpg".equals( img )) {
            File file = new File( rootPath + img );
            if (file.isFile()) {
                file.delete();
                logger.info( img + "被删除" );

            }

        }
        return "删除成功";
    }

    @RequiresPermissions(value = "课程转笔记")
    @PostMapping("change")
    @ResponseBody
    public String change(Integer id) throws Exception {
        Course courseById = courseService.findCourseById( id );
        NoteBook noteBook = new NoteBook();
        noteBook.setName( courseById.getName() );
        noteBook.setText( courseById.getText() );
        noteBook.setStatus( 0 );
        noteBook.setImg( "/img/noteBook/default.jpg" );
        noteBook.setUser( courseById.getAuthor() );
        Integer pid = courseById.getPId();
        //判断该课程是否有子课程
        if (pid == null ) {
            List<Course> courseByPId = courseService.findCourseByPId( id );
            if (courseByPId.size() > 0)
                return "转换错误，因为该课程包含子课程";
        }
        noteBookService.add( noteBook );
        String img = courseById.getImg();
        courseService.delete( id );
        if (!"/img/course/default.jpg".equals( img )) {
            File file = new File( rootPath + img );
            if (file.isFile()) {
                file.delete();
                logger.info( img + "被删除" );

            }

        }
        return "转换成功";
    }

    @RequiresPermissions(value = "课程导出")
    @GetMapping("outText")
    public void outText(Integer id, HttpServletResponse response) throws Exception {
        Course courseById = courseService.findCourseById( id );
        response.setContentType( "application/x-msdownload" );
        response.setHeader( "Content-Disposition", "attachment;filename=" + URLEncoder.encode( courseById.getName() + ".html", "UTF-8" ) );
        OutputStream out = response.getOutputStream();
        String content = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><style>body{margin:5px;padding:0;}*{margin:0;font-family:\"Helvetica Neue\",Helvetica,Arial,sans-serif;font-size:16px}blockquote{height:30px;line-height:30px;border-left:8px solid #d0e5f2;text-indent:6px;background:#f1f1f1;display:block;margin:10px 0}pre code{display:block;color:inherit;}code{color:#c7254e;border:1px solid #999;font-size:14px;line-height:1.5;margin:5px;padding:5px 8px;background-color:#f1f1f1;border-radius:3px}p{margin:10px 8px;line-height:1.5;font-size:16px}li{line-height:14px}li p{font-size:14px;margin-left:2px;line-height:14px}</style></head>"
                + "<body>" + courseById.getText() + "</body></html>";
        InputStream in = new ByteArrayInputStream( content.getBytes() );
        byte[] buffer = new byte[1024];
        int len = 0;

        while ((len = in.read( buffer )) != -1) {
            out.write( buffer, 0, len );
        }
        in.close();
    }


    //修改text以外的其它属性
    @RequiresPermissions(value = "课程修改")
    @PostMapping("edit")
    @ResponseBody
    public String edit(Integer id, String name, Integer[] ids) {
        List<CourseType> courseTypes = new ArrayList<>();
        if (ids!=null){
            for (Integer integer : ids) {
                courseTypes.add( new CourseType( integer ) );
            }
        }
        courseService.updateCourseTypesById( id, name, courseTypes );
        return "修改成功";
    }
    //修改text以外的其它属性
    @RequiresPermissions(value = "课程上下架")
    @PostMapping("status")
    @ResponseBody
    public String status(Integer id, Integer status) {
        courseService.updateStatus( id ,status);
        return "修改成功";
    }

    @RequiresPermissions(value = "课程修改")
    @GetMapping("edit")
    public String edit(Integer id, Model model) {
        Course courseById = courseService.findCourseById( id );
        model.addAttribute( "course", courseById );
        List<CourseType> courseTypes = courseById.getCourseTypes();
        model.addAttribute( "otherType", courseTypeService.findCourseTypeByIdNotIN( courseTypes ) );
        return "course/editCourse";
    }

    @RequiresPermissions(value = "课程修改")
    @GetMapping("editText")
    public String editText(Integer id, Model model) {
        Course courseById = courseService.findCourseById( id );
        model.addAttribute( "course", courseById );
        return "course/editCourseText";
    }

    @RequiresPermissions(value = "课程修改")
    @PostMapping("editText")
    @ResponseBody
    public String editText(Course course) {

        courseService.updateText( course );
        return "修改成功";

    }

    @RequiresPermissions(value = "课程换图")
    @GetMapping("editImg")
    public String editImg(Integer id, Model model) {
        Course courseById = courseService.findCourseById( id );
        model.addAttribute( "course", courseById );
        return "course/editCourseImg";
    }

    @Value("${img.url.rootPath}")
    private String rootPath;

    @RequiresPermissions(value = "课程换图")
    @PostMapping("editImg")
    @ResponseBody
    public String editImg(Integer id, MultipartFile myfile) throws IOException {
        if (myfile != null) {
            String fileName = myfile.getOriginalFilename();// 文件原名称
            //带点的类型
            Course courseById = courseService.findCourseById( id );
            String type = fileName.indexOf( "." ) != -1 ? fileName.substring( fileName.lastIndexOf( "." ), fileName.length() ) : null;
            String newName = UuidUtil.getUUid();
            File file1 = new File( rootPath + "img/course/" + newName+courseById.getName() + type );
            String img = courseById.getImg();


            if (!"/img/course/default.jpg".equals( img )) {
                File file = new File( rootPath + img );
                if (file.isFile()) {
                    file.delete();
                    logger.info( img + "被删除" );
                }

            }


            myfile.transferTo( file1 );
            logger.info( file1.getName() + "被创建" );
            courseService.updateImg( id, "/img/course/" + newName +courseById.getName() + type );
            return "上传成功";
        } else {
            return "上传失败";
        }

    }

    @PostMapping("upload")
    @ResponseBody
    @RequiresPermissions(value = "课程图片上传")
    public Map upload(MultipartFile file) throws IOException {
        Subject currentUser = SecurityUtils.getSubject();
        User principal = (User) currentUser.getPrincipal();
        Map<String, Object> map = new HashMap<>();
        if (file != null) {
            String fileName = file.getOriginalFilename();// 文件原名称
            //带点的类型
            String type = fileName.indexOf( "." ) != -1 ? fileName.substring( fileName.lastIndexOf( "." ), fileName.length() ) : null;
            String newName = UUID.randomUUID().toString();
            File file1 = new File( rootPath + "img/courseText/"+ principal.getName()+ newName + type );
            file.transferTo( file1 );
            map.put( "errno", 0 );
            map.put( "data", new String[]{"/img/courseText/" +principal.getName()+ newName + type} );
        } else {
            map.put( "errno", 1 );
            map.put( "data","上传文件空" );
        }

        return map;
    }


}
